<template>
  <div ref="recommendContainer" class="recommend-container" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
    @touchend="handleTouchEnd">
    <div ref="videoWrapper" class="video-wrapper" :style="{
      transform: `translateY(${videoOffsetY}px)`,
      transition: isTransitioning ? 'transform 0.3s cubic-bezier(0.4, 0, 0.2, 1)' : 'none'
    }">
      <div v-if="previousVideo" class="video-item video-prev" :key="`prev-${currentIndex - 1}`">
        <VideoCardContent :video="previousVideo" :show-info="false" />
      </div>

      <div class="video-item video-current" :key="`current-${currentIndex}`" :class="{ 'comment-mode': showComment }">
        <VideoCardContent :video="currentVideo" :show-info="showInfo && !showComment" :show-comment="showComment"
          @toggle-info="toggleInfoVisibility" @video-play="handleVideoPlay" @video-pause="handleVideoPause"
          @toggle-comment="toggleComment" @close-comment="closeComment" @timeupdate="handleTimeUpdate" />
      </div>

      <div v-if="nextVideo" class="video-item video-next" :key="`next-${currentIndex + 1}`">
        <VideoCardContent :video="nextVideo" :show-info="false" />
      </div>
    </div>

    <div v-if="isLastVideo && isLoadingMore" class="bottom-loading">
      <van-loading type="spinner" color="#1989fa" />
      <span class="loading-text">加载中...</span>
    </div>

    <div v-if="loading && recommendData.length === 0" class="center-loading">
      <van-loading type="spinner" color="#1989fa" />
      <span class="loading-text">加载中...</span>
    </div>

    <div v-if="!loading && recommendData.length === 0" class="empty-state">
      <van-empty description="暂无推荐内容" />
    </div>

    <!-- 评论面板 -->
    <div v-if="hasOpenedComment" class="comment-panel" :class="{ 'show': showComment, 'dark-mode': isDarkMode }"
      @click.stop @touchstart.stop="handleCommentTouchStart" @touchmove.stop="handleCommentTouchMove" @touchend.stop>
      <div class="comment-header">
        <span class="comment-title">评论区</span>
      </div>
      <div class="comment-content-wrapper" ref="commentContentWrapper">
        <CommentList :items="commentList" :has-more="!!commentNextPageUrl" :loading="loadingComments"
          :theme="isDarkMode ? 'dark' : 'light'" @load-more="loadMoreComments" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from 'vue';
import { showNotify } from 'vant';
import { getHot, getByFullUrl, getVideoReplies } from '@/api/api';
import { useWatchHistoryStore } from '@/stores/watchHistory';
import { useDarkModeStore } from '@/stores/darkMode';
import VideoCardContent from './VideoCardContent.vue';
import CommentList from '@/components/CommentList.vue';

const darkModeStore = useDarkModeStore();
const isDarkMode = computed(() => darkModeStore.isDarkMode);

// 数据状态
const recommendData = ref<any[]>([]);
const loading = ref(false);
const nextPageUrl = ref<string | null>(null);
const isLoadingMore = ref(false);
const hasMore = ref(true);

// 观看记录
const watchHistoryStore = useWatchHistoryStore();

// UI状态
const showInfo = ref(true);
const showComment = ref(false);
const recommendContainer = ref<HTMLElement | null>(null);
const videoWrapper = ref<HTMLElement | null>(null);

// 评论相关状态
const commentList = ref<any[]>([]);
const commentNextPageUrl = ref<string | null>(null);
const loadingComments = ref(false);
const commentContentWrapper = ref<HTMLElement | null>(null);
const hasOpenedComment = ref(false); // 是否已点击过评论按钮（控制是否渲染评论面板）

// 触摸滑动状态
const touchStartY = ref(0);
const touchStartX = ref(0);
const touchStartTime = ref(0);
const isSwiping = ref(false);
const currentIndex = ref(0);
const videoOffsetY = ref(0);
const isTransitioning = ref(false);

// 计算属性
const currentVideo = computed(() => {
  return recommendData.value[currentIndex.value] || null;
});

const previousVideo = computed(() => {
  return currentIndex.value > 0 ? recommendData.value[currentIndex.value - 1] : null;
});

const nextVideo = computed(() => {
  return currentIndex.value < recommendData.value.length - 1 ? recommendData.value[currentIndex.value + 1] : null;
});

const isLastVideo = computed(() => {
  return currentIndex.value >= recommendData.value.length - 1;
});

// 切换信息栏显示/隐藏
const toggleInfoVisibility = () => {
  showInfo.value = !showInfo.value;
};

// 切换评论面板显示/隐藏
const toggleComment = async () => {
  if (showComment.value) {
    closeComment();
  } else {
    await openComment();
  }
};

// 打开评论面板
const openComment = async () => {
  if (!currentVideo.value?.id) return;

  // 首次点击评论按钮，标记为已打开过
  if (!hasOpenedComment.value) {
    hasOpenedComment.value = true;
  }

  showComment.value = true;

  // 如果评论列表为空，加载评论
  if (commentList.value.length === 0) {
    await loadComments();
  }
};

// 关闭评论面板
const closeComment = () => {
  showComment.value = false;
};

// 加载评论
const loadComments = async () => {
  if (!currentVideo.value?.id) return;

  loadingComments.value = true;
  try {
    const data: any = await getVideoReplies(currentVideo.value.id);
    if (data?.itemList) {
      commentList.value = data.itemList;
      commentNextPageUrl.value = data.nextPageUrl || null;
    }
  } catch (error) {
    console.error('加载评论失败:', error);
  } finally {
    loadingComments.value = false;
  }
};

// 加载更多评论
const loadMoreComments = async () => {
  if (!commentNextPageUrl.value || loadingComments.value) return;

  loadingComments.value = true;
  try {
    const url = normalizeNextUrl(commentNextPageUrl.value);
    const data: any = await getByFullUrl(url.startsWith('/') ? url : `/${url}`);
    if (data?.itemList) {
      commentList.value.push(...data.itemList);
      commentNextPageUrl.value = data.nextPageUrl || null;
    }
  } catch (error) {
    console.error('加载更多评论失败:', error);
  } finally {
    loadingComments.value = false;
  }
};

// 处理评论面板的触摸开始事件（阻止事件冒泡到父容器）
const handleCommentTouchStart = (e: TouchEvent) => {
  // 阻止事件冒泡到父容器，避免触发视频切换
  e.stopPropagation();
};

// 处理评论面板的触摸移动事件（阻止事件冒泡到父容器，允许内部滚动）
const handleCommentTouchMove = (e: TouchEvent) => {
  // 阻止事件冒泡到父容器，避免触发视频切换
  // 但允许内部的滚动行为
  e.stopPropagation();
};

// 处理视频播放事件
const handleVideoPlay = () => {
  // 视频开始播放时，添加观看记录
  if (currentVideo.value) {
    watchHistoryStore.addHistory(currentVideo.value);
  }
};

// 处理视频暂停事件
const handleVideoPause = () => {
  // 可以在这里添加暂停相关逻辑
};

// 处理视频播放进度更新
const handleTimeUpdate = (currentTime: number) => {
  if (currentVideo.value?.id) {
    watchHistoryStore.updateWatchProgress(currentVideo.value.id, currentTime);
  }
};

// 处理触摸开始事件
const handleTouchStart = (e: TouchEvent) => {
  if (!e.touches || e.touches.length === 0) return;
  const touch = e.touches[0];
  if (!touch) return;
  touchStartY.value = touch.clientY;
  touchStartX.value = touch.clientX;
  touchStartTime.value = Date.now();
  isSwiping.value = false;
};

// 处理触摸移动事件
const handleTouchMove = (e: TouchEvent) => {
  if (!touchStartY.value || !e.touches || e.touches.length === 0) return;
  const touch = e.touches[0];
  if (!touch) return;

  const currentY = touch.clientY;
  const currentX = touch.clientX;
  const deltaY = currentY - touchStartY.value;
  const deltaX = currentX - touchStartX.value;

  // 如果评论面板显示，禁止滑动切换视频
  if (showComment.value) {
    e.preventDefault();
    return;
  }

  // 如果正在加载更多且是最后一个，禁止向上滑动（切换到下一个）
  if (isLoadingMore.value && isLastVideo.value && deltaY < 0) {
    e.preventDefault();
    return;
  }

  // 判断是否为垂直滑动
  if (Math.abs(deltaY) > Math.abs(deltaX) && Math.abs(deltaY) > 10) {
    isSwiping.value = true;

    // 实时更新视频位置
    if (!isTransitioning.value) {
      videoOffsetY.value = deltaY;
    }

    e.preventDefault();
  }
};

// 处理触摸结束事件
const handleTouchEnd = (e: TouchEvent) => {
  // 如果评论面板显示，不处理滑动切换
  if (showComment.value) {
    touchStartY.value = 0;
    touchStartX.value = 0;
    videoOffsetY.value = 0;
    isSwiping.value = false;
    return;
  }

  if (!isSwiping.value || !touchStartY.value) {
    touchStartY.value = 0;
    touchStartX.value = 0;
    videoOffsetY.value = 0;
    return;
  }

  if (!e.changedTouches || e.changedTouches.length === 0) {
    touchStartY.value = 0;
    touchStartX.value = 0;
    videoOffsetY.value = 0;
    isSwiping.value = false;
    return;
  }

  const changedTouch = e.changedTouches[0];
  if (!changedTouch) {
    touchStartY.value = 0;
    touchStartX.value = 0;
    videoOffsetY.value = 0;
    isSwiping.value = false;
    return;
  }

  const endY = changedTouch.clientY;
  const deltaY = endY - touchStartY.value;
  const deltaTime = Date.now() - touchStartTime.value;
  const containerHeight = recommendContainer.value?.clientHeight || window.innerHeight;

  // 滑动阈值配置
  const minDistance = 80;
  const fastSwipeDistance = 50;
  const fastSwipeTime = 300;
  const minDistanceRatio = containerHeight * 0.25;

  // 判断是否满足切换条件
  if (
    Math.abs(deltaY) > minDistance ||
    Math.abs(deltaY) > minDistanceRatio ||
    (Math.abs(deltaY) > fastSwipeDistance && deltaTime < fastSwipeTime)
  ) {
    if (deltaY < 0) {
      // 向上滑动：切换到下一个
      if (isLastVideo.value && isLoadingMore.value) {
        videoOffsetY.value = 0;
        showNotify({
          type: 'warning',
          message: '数据正在加载中，请耐心等待哦~',
          duration: 2000
        });
        return;
      }
      switchToNextWithAnimation();
    } else {
      // 向下滑动：切换到上一个
      switchToPreviousWithAnimation();
    }
  } else {
    // 距离不够，回弹到原位置
    videoOffsetY.value = 0;
  }

  // 重置触摸状态
  touchStartY.value = 0;
  touchStartX.value = 0;
  isSwiping.value = false;
};

// 切换到下一个视频
const switchToNextWithAnimation = () => {
  if (currentIndex.value < recommendData.value.length - 1) {
    // 还有下一个，执行切换动画
    isTransitioning.value = true;
    const containerHeight = recommendContainer.value?.clientHeight || window.innerHeight;

    // 向上滑动整个容器
    videoOffsetY.value = -containerHeight;

    setTimeout(() => {
      // 更新索引
      currentIndex.value++;

      // 重置位置
      nextTick(() => {
        videoOffsetY.value = 0;
        isTransitioning.value = false;
      });
    }, 300);
  } else {
    // 已经是最后一个
    if (isLoadingMore.value) {
      // 如果正在加载，只回弹并显示提示
      videoOffsetY.value = 0;
      showNotify({
        type: 'warning',
        message: '数据正在加载中，请耐心等待哦~',
        duration: 2000
      });
    } else if (hasMore.value) {
      // 还有更多数据，触发加载更多
      videoOffsetY.value = 0;
      isTransitioning.value = true;
      setTimeout(() => {
        isTransitioning.value = false;
        loadMore();
      }, 200);
    } else {
      // 没有更多数据了，只回弹
      videoOffsetY.value = 0;
      isTransitioning.value = true;
      setTimeout(() => {
        isTransitioning.value = false;
      }, 200);
    }
  }
};

// 切换到上一个视频
const switchToPreviousWithAnimation = () => {
  if (currentIndex.value > 0) {
    isTransitioning.value = true;
    const containerHeight = recommendContainer.value?.clientHeight || window.innerHeight;

    // 向下滑动整个容器
    videoOffsetY.value = containerHeight;

    setTimeout(() => {
      // 更新索引
      currentIndex.value--;

      // 重置位置
      nextTick(() => {
        videoOffsetY.value = 0;
        isTransitioning.value = false;
      });
    }, 300);
  } else {
    // 已经是第一个，回弹
    videoOffsetY.value = 0;
    isTransitioning.value = true;
    setTimeout(() => {
      isTransitioning.value = false;
    }, 200);
  }
};

// 获取推荐内容
const fetchRecommendData = async () => {
  loading.value = true;
  try {
    const data: any = await getHot();
    if (data.itemList && data.itemList.length > 0) {
      // 提取视频数据
      recommendData.value = [];
      data.itemList.forEach((item: any) => {
        if (item.type === 'video') {
          recommendData.value.push(item.data);
        } else if (item.type === 'squareCardCollection' && item.data?.itemList) {
          // 处理卡片集合
          item.data.itemList.forEach((card: any) => {
            if (card.type === 'video') {
              recommendData.value.push(card.data);
            }
          });
        }
      });
    }
    nextPageUrl.value = data.nextPageUrl || null;
    hasMore.value = Boolean(nextPageUrl.value);

    // 重置当前索引
    currentIndex.value = 0;
  } catch (err) {
    console.error('获取推荐内容失败:', err);
  } finally {
    loading.value = false;
  }
};

const normalizeNextUrl = (url: string): string => {
  if (!url) return '';
  try {
    const u = new URL(url);
    return u.pathname + u.search;
  } catch {
    return url;
  }
};

// 加载更多
const loadMore = async () => {
  if (isLoadingMore.value || !hasMore.value || !nextPageUrl.value) return;
  isLoadingMore.value = true;

  try {
    const url = normalizeNextUrl(nextPageUrl.value);
    const data: any = await getByFullUrl(url.startsWith('/') ? url : `/${url}`);
    if (data?.itemList?.length) {
      const previousLength = recommendData.value.length;
      data.itemList.forEach((item: any) => {
        if (item.type === 'video') {
          recommendData.value.push(item.data);
        } else if (item.type === 'squareCardCollection' && item.data?.itemList) {
          // 处理卡片集合
          item.data.itemList.forEach((card: any) => {
            if (card.type === 'video') {
              recommendData.value.push(card.data);
            }
          });
        }
      });

      // 如果有新数据，自动切换到第一个新加载的视频
      if (recommendData.value.length > previousLength) {
        const nextIndex = previousLength;
        currentIndex.value = nextIndex;
      }
    }
    nextPageUrl.value = data.nextPageUrl || null;
    hasMore.value = Boolean(nextPageUrl.value);
  } catch (e) {
    console.error('加载更多失败:', e);
  } finally {
    isLoadingMore.value = false;
  }
};

// 监听当前索引变化：切换视频时重置状态
watch(
  () => currentIndex.value,
  () => {
    showInfo.value = true;
    showComment.value = false;
    videoOffsetY.value = 0;
    // 清空评论列表，下次打开时重新加载
    commentList.value = [];
    commentNextPageUrl.value = null;
    // 重置评论面板渲染状态，新视频需要重新点击评论按钮才会渲染
    hasOpenedComment.value = false;
  }
);

// 组件挂载时获取数据
onMounted(() => {
  fetchRecommendData();
});
</script>

<style scoped lang="less">
.recommend-container {
  width: 100%;
  height: calc(100vh - 12vh);
  position: relative;
  background-color: #000;
  overflow: hidden;
  touch-action: pan-y;
  user-select: none;
  z-index: 1;
}

.video-wrapper {
  width: 100%;
  position: relative;
  will-change: transform;
  height: calc(100vh - 12vh);
}

.video-item {
  position: absolute;
  left: 0;
  width: 100%;
  height: calc(100vh - 12vh);
  background-color: #000;
  transition: height 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &.video-prev {
    top: calc(-100vh + 12vh);
    /* 负的容器高度 */
    z-index: 1;
  }

  &.video-current {
    top: 0;
    z-index: 2;

    &.comment-mode {
      height: calc((100vh - 12vh) * 0.3);
    }
  }

  &.video-next {
    top: calc(100vh - 12vh);
    /* 容器高度 */
    z-index: 1;
  }
}

.bottom-loading {
  position: absolute;
  bottom: 100px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  z-index: 100;
  padding: 15px 25px;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 20px;

  .loading-text {
    color: #fff;
    font-size: 12px;
  }
}

.center-loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  z-index: 100;
  padding: 15px 25px;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 20px;

  .loading-text {
    color: #fff;
    font-size: 12px;
  }
}

.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 100;
}

.comment-panel {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: calc((100vh - 12vh) * 0.7);
  background-color: #fff;
  transform: translateY(100%);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1), background-color 0.3s ease;
  z-index: 100;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  touch-action: pan-y;

  &.show {
    transform: translateY(0);
  }

  .comment-header {
    flex-shrink: 0;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 3vw;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    transition: border-color 0.3s ease;

    .comment-title {
      font-size: 16px;
      font-weight: 500;
      color: #000;
      transition: color 0.3s ease;
    }
  }

  .comment-content-wrapper {
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: contain;
    position: relative;
    min-height: 0;
    touch-action: pan-y;
    will-change: scroll-position;
  }

  // 夜间模式样式
  &.dark-mode {
    background-color: #2a2a2a;

    .comment-header {
      border-bottom-color: rgba(255, 255, 255, 0.1);

      .comment-title {
        color: #fff;
      }
    }
  }
}
</style>